<?php

/**
 * @file
 * Menu callbacks for bookcrossing site.
 */

/**
 * Menu callback: book releasing page.
 */
function bookcrossing_release_book_page() {
  if (user_access('release book')) {
    return drupal_get_form('bookcrossing_release_book_form');
  }

  /**
   * @todo add page output for unauthorized users.
   */
}

/**
 * Menu callback: reserve bcid.
 */
function bookcrossing_reserve_bcid($js = 'ajax') {
  if ($js == 'ajax') {
    global $user;

    $bcids = db_select('bookcrossing_books', 'b')
        ->fields('b', array('bcid'))
        ->condition('owner', $user->uid, '=')
        ->condition('status', BOOKCROSSING_BOOK_STATUS_RESERVED, '=')
        ->execute()
        ->fetchCol();

    $num = count($bcids);
    if ($num == BOOKCROSSING_RESRVED_BCIDS) {
      return NULL;
    }

    $bcid = bookcrossing_generate_bcid();
    db_insert('bookcrossing_books')
        ->fields(array(
          'nid' => 0,
          'status' => BOOKCROSSING_BOOK_STATUS_RESERVED,
          'owner' => $user->uid,
          'bcid' => $bcid,
          'current_place' => 0,
        ))
        ->execute();

    $commands = array();

    $reserved_html = '<div class="bcid-container" id="' . $bcid . '">';
    $reserved_html .= l('<b>BCID:</b>' . $bcid, 'delete-reserved/' . $bcid, array('attributes' => array('class' => array('use-ajax')), 'html' => TRUE));
    $reserved_html .= '</div>';
    $commands[] = ajax_command_prepend('.reserved-bcids-container', $reserved_html);

    if ($num == BOOKCROSSING_RESRVED_BCIDS - 1) {
      $commands[] = ajax_command_remove('#reserve-bcid');
    }

    $commands[] = ajax_command_remove('#reserve-bcid-description');

    ajax_deliver(array('#type' => $js, '#commands' => $commands));
  }
}

/**
 * Menu callback: delete reserved bcid.
 */
function bookcrossing_delete_reserved_bcid($bcid = '', $js = 'ajax') {
  if ($js == 'ajax') {
    global $user;

    db_delete('bookcrossing_books')
        ->condition('bcid', $bcid, '=')
        ->condition('owner', $user->uid)
        ->condition('status', BOOKCROSSING_BOOK_STATUS_RESERVED)
        ->execute();

    $commands = array();

    $commands[] = ajax_command_remove('#' . $bcid);

    $reserved = db_select('bookcrossing_books', 'b')
        ->fields('b', array('bcid'))
        ->condition('status', BOOKCROSSING_BOOK_STATUS_RESERVED, '=')
        ->condition('owner', $user->uid, '=')
        ->execute()
        ->fetchCol();

    $num = count($reserved);

    if ($num == 0) {
      $commands[] = ajax_command_after('#reserve-bcid', '<div id="reserve-bcid-description">' . t('You can reserve multiple BCID.') . '</div>');
    }

    ajax_deliver(array('#type' => $js, '#commands' => $commands));
  }
}

/**
 * Menu callback: html output for a front page.
 */
function bookcrossing_front_page() {
  $bids = db_select('bookcrossing_books', 'b')
      ->fields('b', array('bid'))
      ->condition('status', BOOKCROSSING_BOOK_STATUS_RESERVED, '<>')
      ->range(0, 3)
      ->orderRandom('bid')
      ->execute()
      ->fetchCol();
  $books = bookcrossing_load_multiple($bids);

  $output = '';
  foreach ($books as $book) {
    $view = node_view($book['node'], 'front_page');
    $build = bookcrossing_prepare_book_view($view, $book);
    $output .= render($build);
  }

  return $output . '<div style="clear: left"></div>';
}

/**
 * Menu callback: release book.
 */
function bookcrossing_release_book($book) {
  /**
   * Book wasnt found in db.
   */
  if (!$book) {
    return array(
      '#markup' => t('There is no book with that BCID.'),
    );
  }

  /**
   * Book is already released.
   */
  if (!$book['status']) {
    return array(
      '#markup' => t('Cannot to release book because its already was released.'),
    );
  }

  global $user;
  /**
   * Can only release books user reading.
   */
  if ($book['user']->uid != $user->uid) {
    return array(
      '#markup' => t('You cannot release this book because u are not reading it now.'),
    );
  }

  $build = node_view($book['node'], 'found_book');

  /**
   * Form for adding comment and place.
   */
  $build['book_found'] = drupal_get_form('bookcrossing_book_comment', $book);

  /**
   * Status of the found book.
   */
  $build['book_found_status'] = array(
    '#markup' => bookcrossing_book_status($book),
  );

  return $build;
}

/**
 * Menu callback: change users comment.
 */
function bookcrossing_change_comment($bid = '', $js = 'ajax') {
  if ($js == 'ajax') {
    global $user;

    $is_read_book = db_select('bookcrossing_history', 'h')
        ->fields('h', array('bid'))
        ->condition('uid', $user->uid, '=')
        ->condition('bid', $bid, '=')
        ->execute()
        ->fetchField();

    if (!$is_read_book) {
      return NULL;
    }

    $info = array(
      'uid' => $user->uid,
      'bid' => $bid,
    );


    $form = drupal_get_form('bookcrossing_change_comment_form', $info);

    ajax_deliver(array('#type' => $js, '#commands' => array(ajax_command_html('#my-comment-text', render($form)))));
  }
}

/**
 * Menu callback: view histroy page.
 */
function bookcrossing_view_history($history) {
  $build = node_view($history['node'], 'history');
  global $user;

  /**
   * Adding comment of the logged user to the output.
   */
  $my_comment = '<div id="my-comment-text">';
  if (isset($history['comments'][$user->uid])) {
    $my_comment .= $history['comments'][$user->uid];
  }
  $my_comment .= '</div>';

  $is_read_book = db_select('bookcrossing_history', 'h')
      ->fields('h', array('bid'))
      ->condition('uid', $user->uid, '=')
      ->condition('bid', $history['bid'], '=')
      ->execute()
      ->fetchField();

  if ($is_read_book) {
    $change_link = l(t('(change)'), 'change-comment/' . $history['bid'], array('attributes' => array('class' => array('use-ajax'))));
  }
  $build['book_comment'] = array(
    '#markup' => '<div class="back-to-book">' . l(t('<<back to book'), 'book/' . $history['bid']) . '</div><div class="my-comment"><div class="my-comment-title">' . t('My review') . $change_link . '</div>' . $my_comment . '</div>',
  );

  /**
   * Generate output for history of the book.
   */
  $output = '<div class="history-wrapper">';
  foreach ($history['places'] as $place) {
    $comment = isset($history['comments'][$place['user']->uid]) ? $history['comments'][$place['user']->uid] : '';
    $my_comment_class = $place['user']->uid == $user->uid ? ' m-c' : '';
    $output .= '<div class="place-wrapper clearfix">
                  <div class="history-comment' . $my_comment_class . '">' . $comment . '</div>
                  <div class="history-user-foto">foto</div>
                  <div class="history-user-info">'
        . l($place['user']->name, 'user/' . $place['user']->uid)
        . '<div class="history-places">';

    if ($place['place']) {
      $output .= '<div class="place-found">' . t('Found') . ':<div class="place-date-found">' . format_date($place['found']) . ',' . $place['place']->name . '</div></div>';
    }

    if ($place['place_left']) {
      $output .= '<div class="place-left">' . t('Release') . ':<div class="place-date-left">' . format_date($place['time_left']) . ',' . $place['place_left']->name . '</div></div>';
    }

    $output .= '</div></div></div>';
  }
  $output .= '</div>';

  $build['book_history'] = array(
    '#markup' => $output,
  );

  /**
   * Generate item list with status of the book.
   */
  $build['book_status'] = array(
    '#markup' => bookcrossing_book_status($history),
  );

  $build['history_pager'] = array(
    '#theme' => 'pager',
  );

  return $build;
}

/**
 * Menu callback: shows book.
 */
function bookcrossing_view_book($book = array()) {
  $build = node_view($book['node'], 'default');
  $build = bookcrossing_prepare_book_view($build, $book);

  /**
   * Generate output for status of the book.
   */
  $build['book_status'] = array(
    '#markup' => bookcrossing_book_status($book),
  );

  /**
   * Generate links for book: release, view history, add to favourites.
   */
  $items = array();

  global $user;
  if ($user->uid == $book['user']->uid && $book['status']) {
    $items[] = l(t('Release'), 'release-book/' . $book['bid']);
  }

  $items[] = l(t('View history'), 'view-history/' . $book['bid']);

  if ($user->uid) {
    /**
     * @todo add facebook like.
     */
    $items[] = l(t('Add to favourites'), 'add-to-favourites/' . $book['bid'], array('attributes' => array('id' => 'add-to-favourites', 'class=')));
  }

  $build['book_links'] = array(
    '#markup' => theme_item_list(array('title' => '', 'items' => $items, 'type' => 'ul', 'attributes' => array('class' => 'book-links'))),
  );

  return $build;
}


/**
 * Menu callback: page for registering found book.
 */
function bookcrossing_found_book_page($bcid = '') {
  if (empty($bcid)) {
    return '';
  }

  $book = bookcrossing_load_by_bcid($bcid);

  /**
   * There is no that book in db.
   */
  if (!$book) {
    return array(
      '#markup' => t('There is no book with that BCID.'),
    );
  }

  /**
   * Someone already found this book.
   */
  if ($book['status']) {
    return array(
      '#markup' => t('Someone is already reading this book.'),
    );
  }

  $build = node_view($book['node'], 'found_book');
  $build = bookcrossing_prepare_book_view($build, $book, FALSE);
  $build['book_found'] = drupal_get_form('bookcrossing_book_comment', $book);

  /**
   * Generate output for found book status.
   */
  $status_string = $book['status'] ? t('Found') : t('Free book');
  $items = array(
    '<div class="status-label">' . t('Status') . ':</div>' . $status_string,
  );

  if ($book['status']) {
    $items[] = '<div class="status-label">' . t('Reader') . ':</div>' . l($book['user']->name, 'user/' . $book['user']->uid);
  }
  else {
    $items[] = '<div class="status-label">' . t('Released') . ':</div>' . l($book['user']->name, 'user/' . $book['user']->uid) . ', ' . format_date($book['time_left']);
  }

  $build['book_found_status'] = array(
    '#markup' => theme('item_list', array('title' => '', 'items' => $items, 'type' => 'ul', 'attributes' => array('class' => 'status-info'))),
  );

  return $build;
}

/**
 * Form for addding reserved book.
 */
function bookcrossing_add_reserved_book_form($bcid = '') {
  global $user;

  // check if we have reserved bcids
  $reserved = db_select('bookcrossing_books', 'b')
      ->fields('b', array('bcid'))
      ->condition('bcid', $bcid, '=')
      ->condition('owner', $user->uid, '=')
      ->condition('status', BOOKCROSSING_BOOK_STATUS_RESERVED, '=')
      ->execute()
      ->fetchField();

  if ($reserved) {
    $types = node_type_get_types();
    $node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'bookcrossing', 'language' => LANGUAGE_NONE);
    drupal_set_title(t('Create @name', array('@name' => $types['bookcrossing']->name)), PASS_THROUGH);
    return drupal_get_form('bookcrossing_node_form', $node, $bcid);
  }
}

/**
 * Menu callback: page for showing bcid of added book
 */
function bookcrossing_book_added($bcid = '') {
  if (empty($bcid)) {
    return '';
  }

  $output = '<div class="bcid-wrapper"><div class="bcid-number-wrapper">';
  $output .= '<div class="bcid-number">' . t('This is the number of your book') . '<br />(BookcrossingID):</div>';
  $output .= '<div class="bcid">' . $bcid . '</div>';
  $output .= '<div class="bcid-descr">' . t('Write it on your book.') . '</div>';
  $output .= '</div></div>';

  return $output;
}
